import os
import shutil
from django.shortcuts import render
from django.conf import settings
from apps.plugins.gitRepo import GitRepository
from apps.plugins.ssh import SSHProxy


def fetch_code(request):
    if request.method == 'POST':
        # 获取代码
        # 1. 下载代码
        repo = request.POST.get('repo')
        project_name = request.POST.get('project')
        local_path = os.path.join(settings.CODE_PATH, project_name)
        # print(local_path)
        git = GitRepository(local_path, repo)

        # 2. 压缩文件
        abs_file_path = shutil.make_archive(
            base_name=os.path.join(settings.ZIPFILE_PATH, project_name),
            format='zip',
            root_dir=local_path,
        )
        # 3. 上传到指定服务器
        with SSHProxy('192.168.16.98', 22, 'root', settings.SECRET_ID_RSA_PATH) as proxy:
            proxy.upload(abs_file_path, '/data/zcycode.zip')

    return render(request, 'code.html', )
